<?php

namespace app\api\controller;

use app\api\controller\plus\activity\Product;
use app\api\model\order\Order;
use app\api\model\page\Page as AppPage;
use app\api\model\plus\agent\Referee;
use app\api\model\plus\coupon\Coupon;
use app\api\model\plus\coupon\UserCoupon;
use app\api\model\settings\Setting as SettingModel;
use app\api\model\store\Store;
use app\api\model\supplier\Supplier;
use app\api\model\user\User;
use app\api\service\CheckPoint;
use app\common\enum\settings\SettingEnum;
use app\common\model\app\AppUpdate as AppUpdateModel;
use app\common\model\plus\agent\Setting;
use app\common\model\plus\coupon\UserPromoterCoupon;
use app\common\model\product\ProductFormwork;
use app\common\model\product\ProductUnit;
use app\common\model\product\ProductTemplate;
use app\common\model\product\ProductWarehouse;
use app\common\model\store\StoreLook;
use app\common\model\supplier\Service as ServiceModel;
use app\common\model\settings\WxCustomer as WxCustomerModel;
use app\api\model\plus\chat\Chat as ChatModel;
use app\api\model\user\UserAddress as UserAddressModel;
use app\api\model\order\Order as OrderModel;
use app\api\model\settings\Shoptime as ShoptimeModel;
use app\api\model\product\Product as ProductModel;
use app\common\model\settings\Region as RegionModel;
use app\Request;
use app\shop\model\file\UploadFile as UploadFileModel;
use think\facade\Db;
use think\facade\Filesystem;
use think\Model;
use think\facade\Cache;

/**
 * 页面控制器
 */
class Index extends Controller
{
	/**
	 * 首页
	 */
	public function index($page_id = null, $url = '')
	{
		// 页面元素
		$data = AppPage::getPageData($this->getUser(false), $page_id);
		//消息条数
		$Chat = new ChatModel;
		$data['msgNum'] = $Chat->mCount($this->getUser(false));
		$data['setting'] = array(
			'collection' => SettingModel::getItem('collection'),
			'officia' => SettingModel::getItem('officia'),
			'homepush' => SettingModel::getItem('homepush'),
		);
		// 扫一扫参数
		$data['signPackage'] = $this->getScanParams($url)['signPackage'];
		return $this->renderSuccess('', $data);
	}

	public function getCouponList(Request $request)
	{
		$pamas = $request->param();
		$user = $this->getUser();
		$Shopinfo = $this->getUserCache();
		return $this->renderSuccess('', (new Coupon())->getList($user, $pamas['limit'], true,$Shopinfo['shop'],1,$Shopinfo['city']));
	}

    /**
     * 获取新人满减优惠券
     * @param Request $request
     * @return \think\response\Json
     * @throws \app\common\exception\BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getNewPeopleCouponList(Request $request){
        $pamas = $request->param();
        $user = $this->getUser();
        $Shopinfo = $this->getUserCache();
        $list = $this->renderSuccess('', (new Coupon())->getList($user, $pamas['limit'], true,$Shopinfo['shop'],2,$Shopinfo['city']));
        return $list;
    }

    // 20230225 joey 首页推荐商品去掉新人专享商品
    /**
     * 首页推荐商品列表
     * @param Request $request
     * @return \think\response\Json
     * @throws \app\common\exception\BaseException
     * @Author joey
     * @date 2024/2/25 16:22
     */
    public function getProduct(Request $request)
	{
		$params = $request->param();
		$user = $this->getUser();
		// 获取商品数据
		$model = new ProductModel;
		// 数据来源：自动
		/*$productList = $model->getList([
			'type' => 'sell',
			'category_id' => $params['category_id'],
			'sortType' => 'all',
			'list_rows' => $params['list_rows'],
			'audit_status' => 10,
			'recommend' => $params['recommend'],
		], $user);*/
        $productList = $model->getProductListByType([
            'category_id' => $params['category_id'],
            'list_rows' => $params['list_rows'],
            'audit_status' => 10,
            'is_show' => 1,
            'recommend' => $params['recommend'],
        ], $user, 0);
		return $this->renderSuccess('', $productList);
	}

    /**
     * 自动执行任务
     * @return void
     */
     public function  crontab(){

         //订单超时3分钟不接单自动取消订单
         (new OrderModel()) -> getRedisOrder();
     }

	/**
	 * 首页
	 */
	public function diy($page_id = null, $url = '')
	{
		// 页面元素
		$data = AppPage::getPageData($this->getUser(false), $page_id);
		// 微信公众号分享参数
		$data['share'] = $this->getShareParams($url, $data['page']['params']['share_title'], $data['page']['params']['share_title'], '/pages/diy-page/diy-page', $data['page']['style']['toplogo']);
		return $this->renderSuccess('', $data);
	}

	

	// 公众号客服
	public function mpService($shop_supplier_id)
	{
		$mp_service = ServiceModel::detail($shop_supplier_id);
		return $this->renderSuccess('', compact('mp_service'));
	}

	//底部导航
	public function nav()
	{
		$data['vars'] = SettingModel::getItem(SettingEnum::NAV);
		$data['theme'] = SettingModel::getItem(SettingEnum::THEME);
		$data['points_name'] = SettingModel::getPointsName();
		return $this->renderSuccess('', $data);
	}

	// app更新
	public function update($name, $version, $platform)
	{
		$result = [
			'update' => false,
			'wgtUrl' => '',
			'pkgUrl' => '',
		];
		try {
			$model = AppUpdateModel::getLast();
			if ($platform == 'android') {
				$compare_version = $model['version_android'];
			} else {
				$compare_version = $model['version_ios'];
			}
			if ($model && str_replace('.', '', $version) < str_replace('.', '', $compare_version)) {
				$currentVersions = explode('.', $version);
				$resultVersions = explode('.', $compare_version);

				if ($currentVersions[0] < $resultVersions[0]) {
					// 说明有大版本更新
					$result['update'] = true;
					$result['pkgUrl'] = $platform == 'android' ? $model['pkg_url_android'] : $model['pkg_url_ios'];
					log_write('大版本');
				} else {
					// 其它情况均认为是小版本更新
					$result['update'] = true;
					$result['wgtUrl'] = $model['wgt_url'];
					log_write('小版本' . $result['wgtUrl']);
				}
			}
		} catch (\Exception $e) {

		}
		return $this->renderSuccess('', compact('result'));
	}

    public function checkUser(){
        $user = $this->getUser();
        $data['user_id'] = $user['user_id'];
        return $this->renderSuccess('',compact('data'));
    }

	public function getCity()
	{
		$user = $this->getUser();
		if (empty($user)) return $this->renderSuccess();
		$province = $this->request->param('province');
		$city = $this->request->param('city');

        $lng = $this->request->param('lng');
        $lat = $this->request->param('lat');

		$usaddrid = $this->request->param('usaddrid');
		$address_id = $usaddrid?:0;
		if($address_id>1000000){
			$address_id = 0;
		}
//        $province = '广西省';
//        $city = "长沙市";
		$default_city_id = 2163;//总部为南宁地区

		$res = Db::name('region')->where('name', 'like', '%' . $city . '%')->where('level', '=', 2)->find();
		$province_id = $res['pid'];
		$city_id = $res['id'];
		$storeList = Db::name('store')->where('city_id', '=', $res['id'])->where('is_delete', '=', 0)->field('shop_supplier_id')->group('shop_supplier_id')->select()->toArray();
		//查找用户地址
		$detail = UserAddressModel::detail($user, $address_id);

        //用户当前坐标
        $lwhere['longitude'] = $lng;
        $lwhere['latitude'] = $lat;

		if($address_id>0&&$detail){
			// 查找地址附近门店
			$lwhere['longitude'] = $detail['longitude'];
			$lwhere['latitude'] = $detail['latitude'];
		}
        if ($lwhere['longitude'] && $lwhere['latitude']) {
            $InsstoreList = OrderModel::checkScope($lwhere);
            if(count($InsstoreList)<=0){
            	$InsstoreList = OrderModel::checkMiniStore($lwhere);
            }
            if(count($InsstoreList)>0){
                $storeList = [];
                foreach ($InsstoreList as $keyy => $vall) {
                    if($vall['city_id'] == $city_id){
                        $storeList[0]['shop_supplier_id'] = $vall['shop_supplier_id'];
                        break;
                    }
                }
            }
        }
		if(!$storeList){
			$storeList = Db::name('store')->where('city_id', '=', $default_city_id)->field('shop_supplier_id')->group('shop_supplier_id')->limit(1)->select()->toArray();
		}
		$tempArr = [];
		$ShopInid = 0;
		foreach ($storeList as $item) {
			array_push($tempArr, $item['shop_supplier_id']);
			if($ShopInid==0){
				$ShopInid = $item['shop_supplier_id'];
			}
		}
		//缓存记录用户-商户
		// Cache::set($user['user_id'] . '_supplier_id', $tempArr);
        //营业状态
        // $supplier = Supplier::whereIn('shop_supplier_id', $tempArr)->field('business_status,name,shop_supplier_id')->find();
        $supplier = Supplier::where('shop_supplier_id' , '=' , $ShopInid)->field('business_status,name,shop_supplier_id,city_id')->find();
		//营业时间 // 20240508 Mr.Z可根据商户定制时间
		$ShoptimeModel = new ShoptimeModel();
		$ShopDayTime = $ShoptimeModel->getBusinessTime($province_id,$city_id,$supplier['shop_supplier_id']);
        if($supplier['city_id']!=$city_id){
            log_write('uid:'.$user['user_id'].'--->shop:'.$ShopInid.'--->city:'.$city_id.'--->store_json:'.json_encode($storeList).'--->request:'.json_encode($this->request->param()), 'task');
        }
		//缓存记录用户-商户
		Cache::set($user['user_id'] . '_supplier_id', $supplier['shop_supplier_id']);
		//缓存记录用户-省/市
		Cache::set($user['user_id'] . '_mycity_numid', [$province_id,$city_id]);
        //缓存记录当前用户所在的前置仓id
        Cache::set($user['user_id'] . '_shop_supplier_id', $supplier['shop_supplier_id']);
		return $this->renderSuccess('',['businesshours'=>$ShopDayTime[0].'-'.$ShopDayTime[1], 'supplier' => $supplier]);
	}

	/**
	 * @Exp    检查是否营业
	 * @Author Mr.Z
	 * @Date   2024-03-01
	 * @return [type]     [checkbusiness：0关门，1开门]
	 */
	public function getCityBusiness()
	{
		$province = $this->request->param('province')??'';
		$city = $this->request->param('city')??'';
		$user = $this->getUser();
		if (empty($user)) return $this->renderSuccess();
		$cityAry = [];
		if($province&&$city){
			$res = Db::name('region')->where('name', 'like', '%' . $city . '%')->where('level', '=', 2)->find();
			if($res){
				$province_id = $res['pid'];
				$city_id = $res['id'];
				$cityAry = [$province_id,$city_id];
			}
		}
		// 20240508 Mr.Z可根据商户定制营业时间
		$Shop_Supplier_Id = Cache::get($user['user_id'] . '_supplier_id');
		$cityAry = count($cityAry)>0?$cityAry:Cache::get($user['user_id'] . '_mycity_numid');
		$ShoptimeModel = new ShoptimeModel();
		$Copen = $ShoptimeModel->checkBusiness($cityAry[0],$cityAry[1],$Shop_Supplier_Id);
		$ShopDayTime = $ShoptimeModel->getBusinessTime($cityAry[0],$cityAry[1],$Shop_Supplier_Id,false);
		$ShopDayTimeC = $ShoptimeModel->getBusinessTime($cityAry[0],$cityAry[1],$Shop_Supplier_Id);

		$Outdate = [
			'checkbusiness'=>$Copen,
			'businesstxt'=>'营业时间'.$ShopDayTimeC[0].'-'.$ShopDayTimeC[1].'，可预约配送！',
			'start_t_h'=>date("H",strtotime(date("Y-m-d ".$ShopDayTime[0]))),
			'start_t_i'=>date("i",strtotime(date("Y-m-d ".$ShopDayTime[0]))),
			'end_t_h'=>date("H",strtotime(date("Y-m-d ".$ShopDayTime[1]))),
			'end_t_i'=>date("i",strtotime(date("Y-m-d ".$ShopDayTime[1]))),
            'make_time_h'=>date("H",strtotime(date("Y-m-d ".$ShopDayTime[0])) + 1800),
			'make_time_i'=>date("i",strtotime(date("Y-m-d ".$ShopDayTime[0]))  + 1800)

		];
		return $this->renderSuccess('', $Outdate);
	}

	public function getCityStore()
	{
		$province = $this->request->param('province');
		$city = $this->request->param('city');
		$res = Db::name('region')->where('name', 'like', '%' . $city . '%')->where('level', '=', 2)->find();
		$storeNum = Db::name('store')->where('city_id', '=', $res['id'])->where('is_delete', '=', 0)->field('shop_supplier_id')->group('shop_supplier_id')->count();

        //根据某些日子改变页面颜色（kevin 2024/5/9）

        $vars['values'] = \app\shop\model\settings\Setting::getItem('store');
        $is_gray_filter_val = $vars['values']['is_gray_filter']??0;
        $is_gray_filter = $is_gray_filter_val?true:false;


        $page_data = [];
        $page_select_icon_ist = [
            [
                'index'=>0,
                'selected_icon_path' => 'https://jiumiaodao.oss-cn-guangzhou.aliyuncs.com/upload/2024-05-09/20240509103406aeb6f0354.png'
            ],
            [
                'index'=>1,
                'selected_icon_path' => 'https://jiumiaodao.oss-cn-guangzhou.aliyuncs.com/upload/2024-05-09/20240509103452774329846.png'
            ],

            [
                'index'=>2,
                'selected_icon_path' => 'https://jiumiaodao.oss-cn-guangzhou.aliyuncs.com/upload/2024-05-09/2024050910355382cfa2989.png'
            ],

            [
                'index'=>3,
                'selected_icon_path' => 'https://jiumiaodao.oss-cn-guangzhou.aliyuncs.com/upload/2024-05-09/20240509103940330942474.png'
            ],
        ];
        $page_data['page_tab_selected_color'] = '#2a2a2a';
        $page_data['is_gray_filter'] = $is_gray_filter;
        $page_data['page_select_icon_ist'] = $page_select_icon_ist;


        if($storeNum>0){
			return $this->renderSuccess('', ['getstore'=>1,'page_data' =>  $page_data]);
		}
		return $this->renderSuccess('', ['getstore'=>0,'page_data' =>  $page_data]);
	}

	public function getWxcustomers(){
		$WxCustomerModel = new WxCustomerModel();
		$kflink = $WxCustomerModel->getCustomers();
		return $this->renderSuccess('', compact('kflink'));
	}


    /**
     * 店铺列表
     * @return \think\response\Json
     * @throws \app\common\exception\BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @Author joey
     * @date 2024/4/7 17:06
     */
    public function storeList()
    {
        $user    = $this->getUser();
        $cityAry = Cache::get($user['user_id'] . '_mycity_numid');
        $supplier = Supplier::with('store')
            ->where(['is_audit' => 1, 'is_recycle' => 0, 'is_delete' => 0])
            ->where(['city_id' => $cityAry[1]])
            ->select();

        if ($supplier->isEmpty()) {
            $supplier = Supplier::with('store')
                ->where(['is_audit' => 1, 'is_recycle' => 0, 'is_delete' => 0])
                ->where(['province_id' => $cityAry[0]])
                ->select();
        }
        return $this->renderSuccess('', compact('supplier'));
    }

    /**
     * @Exp    新人专区文字
     * @Author Mr.Z
     * @Date   2024-05-11
     * @return [type]     [description]
     */
    public function newpeopleText(){
    	$text = [];
    	$text['top_a'] = "新用户专区";
    	$text['top_b'] = "(任选一款)";
    	$text['top_c'] = "享新人专享价";
    	$text['min_a'] = "新人专区内下单";
    	$text['min_b'] = "按订单成交金额";
    	$text['min_c'] = "1:1";
    	$text['min_d'] = "返";
    	$text['bom_a'] = "返利大作战";
    	$text['bom_b'] = "买多少返多少";
    	$text['bom_c'] = "订单完成自动返券";
    	return $this->renderSuccess('', compact('text'));
    }

    //测试用接口
    public function testApi()
    {
        //测试赠送优惠券
        //$order = Order::find(425);
        //$res = Order::giveCoupon($order);
        // $array = [["22.801949608669165", "108.37841033935547"], ["22.801395746423566", "108.39583396911621"], ["22.80851666085812", "108.4017562866211"], ["22.812709914142044", "108.402099609375"], ["22.813105497411698", "108.3962631225586"], ["22.819434673475907", "108.39583396911621"], ["22.821096033451788", "108.39428901672363"], ["22.816665695139765", "108.39042663574219"], ["22.81706126692052", "108.38604927062988"], ["22.818089748173193", "108.38295936584473"], ["22.80859578003925", "108.38278770446777"]];
        // $point = ['22.82365', '108.396524'];
        //测试一
//        CheckPoint::setCoordArray($array);
//        $res = CheckPoint::isCityCenter($point);
        // $res = pointInPolygon($point,$array);
        // return $this->renderSuccess('',compact('res'));
        
        // $RespAry = [0,0];
        // $User = new User;
        // $userlist = $User->where('city_id','=',-1)
        // 	// ->where('is_delete','=',0)
        // 	->field('user_id,country,province,city,create_time,mobile')
        // 	->select();
        // foreach ($userlist as $key => $value) {
        // 	$countryary = User::getUserRegion($value['city'],$value['country']);
        // 	$data = [];
        //     $data['province_id'] = $countryary[0] ?? 0;
        //     $data['city_id'] = $countryary[1] ?? 0;
        //     $data['country_id'] = $countryary[2] ?? 0;
        //     $resp = $User->where('user_id', '=', $value['user_id'])->update($data);
        //     if($resp){
        //     	$RespAry[0]++;
        //     }else{
        //     	$RespAry[1]++;
        //     }
        // }
        // // 更新城市信息
        // $RespAry = [0,0];
        // $User = new User;
        // $userlist = $User->where(function($query){
	       //  	$query->where('city_id','>',0)->whereOr('province_id','>',0)->whereOr('country_id','>',0);
	       //  })
        // 	->where('country','=','')
        // 	->field('user_id,country_id,province_id,city_id,create_time,mobile')
        // 	->select();
        	
        // foreach ($userlist as $key => $value) {
        // 	$countryary = [];
        // 	$country_id = $value['country_id'];
        //     $province_id = $value['province_id'];
        //     $city_id = $value['city_id'];
        //     if($city_id){
        //     	$countryary = RegionModel::getRegionParents($city_id);
        //     }elseif($province_id){
        //     	$countryary = RegionModel::getRegionParents($province_id);
        //     }
        //     $country = "";
        //     $province = "";
        //     $city = "";
        //     if($country_id==86){
        //     	$country = '中国';
        //     }
        //     if(isset($countryary['lv'])){
        //     	$country = '中国';
        //     	$province = $countryary['province']['label'];
        //     	$city = $countryary['city']['label'];
        //     }

        //     $data = [];
        //     $data['country'] = $country;
        //     $data['province'] = $province;
        //     $data['city'] = $city;
        //     $resp = $User->where('user_id', '=', $value['user_id'])->update($data);
        //     if($resp){
        //     // if($country){
        //     	$RespAry[0]++;
        //     	// if($RespAry[0]%10==0){
        //     	// 	dump([$province,$city]);
        //     	// }
        //     }else{
        //     	$RespAry[1]++;
        //     }
        // }
        // dump(['Oknum'=>$RespAry[0],'Errnum'=>$RespAry[1]??0]);exit;
        // $list = (new OrderModel())->where('order_id','>','0')->find();
        // dump($list);exit;
        // for ($i=0; $i < 80000; $i++) { 
        // 	$bcmm = ABCString($i);
        // 	print_r([$i=>$bcmm]);
        // 	echo "<br/>";
        // }
        // exit;

        // 更新商品模板表
//        $oknum = [0,0];
//        $list = ProductTemplate::listAll([],[],'id asc');
////        $list = ProductTemplate::listData([],['list_rows'=>50],[]);
////        dump($list->toarray());exit;
//        foreach ($list as $item) {
////        foreach ($list->toarray()['data'] as $item) {
//            $prors = ProductModel::detail($item['product_id']);
//            if($prors){
//                $data = $prors->toarray();
//                //消除联表数据
//                unset($data['product_id'],$data['product_sku'],$data['product_multi_spec'],$data['category'],$data['image'],$data['sku'],$data['supplier'],$data['product_status']);
//                $namestr = strtoupper($data['product_name']);
//                $namestr = str_replace("MI","ML",$namestr);
//                $namestr = str_replace("灌","罐",$namestr);
//                $namestr = str_replace("听","罐",$namestr);
//                $sku_name = '';
//                $unitname = '';
//                // 单位
//                $pattern = '/(\d+)[罐瓶套听桶]/u';
//                preg_match($pattern, $namestr, $matches);
//                if(count($matches)>1){
//                    $data['unit_num'] = $matches[1];
//                    $unitname = str_replace($matches[1],"",$matches[0]);
//                    $unitid = ProductUnit::findunit(['name'=>$unitname]);
//                    if($unitid){
//                        $data['unit'] = $unitid['unit_id'];
//                    }
//                    $sku_name .= $matches[1];
//                }else{
//                    $data['unit_num'] = 1;
//                    $data['unit'] = 1;
//                    $sku_name .= 1;
//                }
//                // 规格
//                $net_content = $data['net_content'];
//                $sku_name = $net_content!="-"?$net_content."ML".'*'.$sku_name:$sku_name.$unitname;
//                $data['sku_name'] = $sku_name;
//                if(!isset($data['unit'])||!isset($data['unit_num'])||!isset($data['sku_name'])){
//                    $oknum[1]++;
//                    continue;
//                }
//                $data['template_id'] = $item['id'];
//                $data['app_id'] = $this->app_id;
//                $rs = (new ProductFormwork())->save($data);
//                if($rs){
//                    $oknum[0]++;
//                    continue;
//                }
//            }
//            $oknum[1]++;
//        }
//        dump([$oknum[0],$oknum[1]]);
//        exit;

        // 更新商品仓库表
//        $oknum = [0,0,0];
//        $list = ProductModel::where('product_id','>',0)->order('product_id asc')->select()->toArray();
//        foreach ($list as $item) {
//            //消除联表数据
//            unset($item['product_id'],$item['product_sku'],$item['product_multi_spec'],$item['category'],$item['image'],$item['sku'],$item['supplier'],$item['product_status']);
//            $namestr = strtoupper($item['product_name']);//转大写
//            $namestr = $this->rebuildPname($namestr);
//            $item['product_name'] = $namestr;
//            $item['app_id'] = $this->app_id;
//            $temprs = ProductWarehouse::withoutGlobalScope()->where(['product_name'=>$namestr])->find();
//            if($temprs) {
//                dump("group------------>>".$temprs['product_warehouse_id']."<================>".$namestr);
//                $oknum[2]++;
//                continue;
//            }else {
//                $rs = (new ProductWarehouse())->save($item);
//                if($rs){
//                    $oknum[0]++;
//                    continue;
//                }
//            }
//            $oknum[1]++;
//        }
//        dump([$oknum[0],$oknum[1],$oknum[2]]);
//        exit;

        // 更新模板表-仓库id
//        $oknum = [0,0,0];
//        $list = ProductFormwork::withoutGlobalScope()->where('warehouse_id','=',0)->order('formwork_id asc')->field('formwork_id,product_name')->select()->toArray();
//        foreach ($list as $item) {
//            $namestr = strtoupper($item['product_name']);//转大写
//            $namestr = $this->rebuildPname($namestr);
//            $temprs = ProductWarehouse::withoutGlobalScope()->where(['product_name'=>$namestr])->find();
//            if($temprs) {
//                $model = ProductFormwork::detail($item['formwork_id']);
//                if ($model->save(['warehouse_id'=>$temprs['product_warehouse_id']])){
//                    $oknum[0]++;
//                    continue;
//                }
//                $oknum[2]++;
//                continue;
//            }
//            $oknum[1]++;
//        }
//        dump([$oknum[0],$oknum[1],$oknum[2]]);
//        exit;

        // 更新商品表-模板id
//        $oknum = [0,0];
//        $list = (new ProductModel())->where("formwork_id","=",0)->field('product_id,product_name')->order("product_id asc")->select();
//        foreach ($list as $item) {
//            $namestr = $item['product_name'];
//            $Formrs = ProductFormwork::withoutGlobalScope()->where("product_name", "=", $namestr)->field("formwork_id")->find();
//            if($Formrs) {
//                $Pmodel = ProductModel::detail($item['product_id']);
//                // 更新模板id
//                if($Pmodel->save(['formwork_id'=>$Formrs['formwork_id']])){
//                    $oknum[0]++;
//                }
//            }else {
//                if($oknum[1]<20){
//                    dump($namestr);
//                }
//                $oknum[1]++;
//            }
//        }
//        dump([$oknum[0],$oknum[1]]);
//        exit;

//        // 更新商品表-仓库id，单位，规定，父id
//        $oknum = [0,0,0];
//        $list = (new ProductModel())->where("product_id ",">",0)->field('product_id,product_name,formwork_id,net_content')->order("product_id asc")->select();
//        foreach ($list as $item) {
//            $data = [];
//            $namestr = $item['product_name'];
//            $formwork_id = $item['formwork_id'];
//            $getUnit = false;
//            if($formwork_id>0) {
//                $frs = ProductFormwork::detail($formwork_id);
//                if ($frs) {
//                    $data['unit_id'] = $frs['unit'];
//                    $data['unit_num'] = $frs['unit_num'];
//                    $data['sku_name'] = $frs['sku_name'];
//                    $data['warehouse_id'] = $frs['warehouse_id'];
//                    $data['parent_id'] = $frs['warehouse_id'];
//                    $getUnit = true;
//                }
//            }
//            $sku_name = '';
//            $unitname = '';
//            if(!$getUnit){
//                // --设置单位、规格--
//                $renamestr = strtoupper($namestr);//转大写
//                $renamestr = str_replace("MI","ML",$renamestr);
//                $renamestr = str_replace("灌","罐",$renamestr);
//                $renamestr = str_replace("听","罐",$renamestr);
//                // 单位
//                $pattern = '/(\d+)[罐瓶套听桶]/u';
//                preg_match($pattern, $renamestr, $matches);
//                if(count($matches)>1){
//                    $data['unit_num'] = $matches[1];
//                    $unitname = str_replace($matches[1],"",$matches[0]);
//                    $unitid = ProductUnit::findunit(['name'=>$unitname]);
//                    if($unitid){
//                        $data['unit_id'] = $unitid['unit_id'];
//                    }
//                    $sku_name .= $matches[1];
//                }else{
//                    $data['unit_num'] = 1;
//                    $data['unit_id'] = 2;
//                    $sku_name .= 1;
//                }
//                // 规格
//                $net_content = $item['net_content'];
//                $sku_name = $net_content!="-"?$net_content."ML".'*'.$sku_name:$sku_name.$unitname;
//                $data['sku_name'] = $sku_name;
//
//                // 设置仓库
//                $renamestr = $this->rebuildPname($namestr);
//                $temprs = ProductWarehouse::withoutGlobalScope()->where(['product_name'=>$renamestr])->find();
//                if($temprs) {
//                    $data['warehouse_id'] = $temprs['product_warehouse_id'];
//                    $data['parent_id'] = $temprs['product_warehouse_id'];
//                }else{
//                    $oknum[2]++;
//                    continue;
//                }
//            }
//            $Pmodel = ProductModel::detail($item['product_id']);
//            // 更新模板id
//            if($Pmodel->save($data)){
//                $oknum[0]++;
//                continue;
//            }
//            $oknum[1]++;
//        }
//        dump([$oknum[0],$oknum[1],$oknum[2]]);
//        exit;

        //
//        $oknum = [0,0,0];
//        $list = Store::withoutGlobalScope()->where('store_id','>',0)->select()->toArray();
//        foreach ($list as $val){
//            unset($val['region'],$val['is_check'],$val['status']);
//            if (count($val['scope_coordinates'])==0) $val['scope_coordinates']='';
//            $val['app_id'] = $this->app_id;
//            $rs = (new StoreLook)->save($val);
//            if($rs){
//                $oknum[0]++;
//                continue;
//            }
//            $oknum[1]++;
//        }
//        dump([$oknum[0],$oknum[1]]);
//        exit;
    }

    private function rebuildPname($product_name){
        $havexing = false;
        $namestr = str_replace(' ', '', $product_name);//去掉空格
        if (strpos($namestr, "*") !== false) {
            $havexing = true;
//            dump($namestr);
        }
        // 单位1
        $pattern = '/(\d+)(纸箱)/u';
        preg_match($pattern, $namestr, $matches);
        if(count($matches)>1) {
            $namestr = str_replace($matches[0], "", $namestr);//替换掉单位
        }
        // 单位2
        $pattern = '/(\d+)[罐瓶套听灌桶]/u';
        preg_match($pattern, $namestr, $matches);
        if(count($matches)>1) {
            $namestr = str_replace($matches[0]."/箱装", "", $namestr);//替换掉单位
            $namestr = str_replace($matches[0]."/箱", "", $namestr);//替换掉单位
            $namestr = str_replace($matches[0]."装", "", $namestr);//替换掉单位
            $namestr = str_replace($matches[0], "", $namestr);//替换掉单位
        }
        // 单位3
        $pattern = '/[0-9](\*)(\d+)(\*)(\d+)/u';
        preg_match($pattern, $namestr, $matches);
        if(count($matches)>1) {
            $namestr = str_replace($matches[1].$matches[2].$matches[3].$matches[4], "", $namestr);//替换掉单位
        }
        // 单位4
        $pattern = '/[0-9](\*)(\d+)/u';
        preg_match($pattern, $namestr, $matches);
        if(count($matches)>1) {
            $namestr = str_replace($matches[0], "", $namestr);//替换掉单位
        }
        $namestr = str_replace('1*1', '', $namestr);//去掉1*1
        $namestr = str_replace('1*', '', $namestr);//去掉1*
        $namestr = str_replace('*', '', $namestr);//去掉*号
        if($havexing) {
//            dump($namestr);
        }
        return $namestr;
    }


    /**
     * 获取远程服务器图片并保存
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @Author joey
     * @date 2024/3/6 10:35
     */
    public function fileList()
    {
        set_time_limit(0);
        $file_list = UploadFileModel::where('file_url','https://jiumiaodao.oss-cn-guangzhou.aliyuncs.com')->order(['file_id' => 'desc'])
        ->paginate(1000);

		$files = $file_list->toArray();
		$num = 0;
		if ($files['data']) {
		    foreach ($files['data'] as $item) {
		        try {
		            $dir      = explode('/', $item['file_name'], 3);
		            $savePath = public_path() . $dir[1];
		            if (!is_dir($savePath)) {
		                mkdir($savePath, 0777, true);
		            }
		            $url      = $item['file_url'] . '/' . $item['file_name'];
		            $pathname = $savePath . '/' . $dir[2];
		            $filename = file_get_contents($url);
		            file_put_contents($pathname, $filename);
		            $num++;
		        } catch (\Exception $e) {
		            log_write('写入错误：' . $e->getMessage());
		        }
		    }
		}

        return $this->renderSuccess('success', compact('num'));
    }

}
